package com.shitou.springai1.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shitou.springai1.admin.entity.dto.PostDto;
import com.shitou.springai1.admin.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
 @RequestMapping("/admin/api/posts")
public class PostController {

    @Autowired
    private PostService postService;

    // 获取言论列表（分页、搜索、筛选）
    @GetMapping
    public ResponseEntity<?> getPosts(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "6") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "desc") String likeOrder
    ) {
        try {
            // 调用服务层获取言论列表
            IPage<PostDto> postPage = postService.getPostsByPage(pageNum, pageSize, keyword, startDate, endDate, status, likeOrder);

            // 构建响应数据
            Map<String, Object> result = new HashMap<>();
            result.put("total", postPage.getTotal());
            result.put("records", postPage.getRecords());
            result.put("current", postPage.getCurrent());
            result.put("size", postPage.getSize());
            result.put("pages", postPage.getPages());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("获取言论列表失败：" + e.getMessage());
        }
    }

    // 更新言论状态（禁用/启用）
    @PutMapping("/{id}/status")
    public ResponseEntity<?> updatePostStatus(
            @PathVariable Long id,
            @RequestBody Map<String, Integer> requestBody
    ) {
        try {
            // 获取状态参数
            Integer status = requestBody.get("status");

            // 验证参数
            if (id == null || status == null || (status != 0 && status != 1)) {
                return ResponseEntity.badRequest().body("参数错误");
            }

            // 调用服务层更新状态
            boolean success = postService.updatePostStatus(id, status);

            if (success) {
                return ResponseEntity.ok("操作成功");
            } else {
                return ResponseEntity.status(404).body("言论不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("操作失败：" + e.getMessage());
        }
    }
}
